/*
 *      fcompare.cpp
 *      
 *      Copyright 2008 Charlotte Curtis <c.f.curtis@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */


#include <iostream>
#include <fstream>
#include <marsyas/realvec.h>
#include <marsyas/NumericLib.h>
#include <dirent.h>

using namespace std;
using namespace Marsyas;

bool isexcluded(const string &vecfile, const vector<string> &excluded)
{
	if (excluded.size() == 0) return false;
	
	vector<string>::const_iterator iter;
	
	for (iter = excluded.begin(); iter < excluded.end(); iter++)
	{
		if (vecfile.compare(*iter) == 0)
		{
			return true;
		}
	}
	return false;
}

int main(int argc, char** argv)
{
	if (argc < 3) {
		cout << "Usage: " << argv[0] << " folder vector exclude" << endl;
		cout << "returns the best matching song" << endl;
		return 1;
	}
	realvec v1;
	realvec v2;
	
	// empty vector for euclidean distance
	realvec cov;
	mrs_real res;
	
	// the command line options
	chdir(argv[1]);
	DIR *dp = opendir(argv[1]);
	v1.read(argv[2]);
	
	// Hmm... using a char* cut off the first half of the name, weird
	string topmatch_str = "";
	float topmatch_fl = 1.0;
	string vecfilename;
	
	vector<string> excluded(argc-3);
	
	if (argc > 3) {
		for (int i = 3; i < argc; i++)
			excluded.push_back(string(argv[i]));
	}		
	
	struct dirent *ep;
	
	if (dp != NULL)
	{
		while ((ep = readdir(dp)))
		{
			vecfilename = string(ep->d_name);
			if ((int(vecfilename.find(".vec")) != -1) && !isexcluded(vecfilename, excluded))
			{
				v2.read(vecfilename);
				res = NumericLib::euclideanDistance(v1, v2, cov);
				
				if (res != 0 && res < topmatch_fl)
				{
					topmatch_fl = res;
					topmatch_str = vecfilename;
				}
			}
		}
	}
	
	cout << topmatch_str << endl;
	return 0;
}
